package cn.edu.hrbcu.es.invigilatemanagerment.configuration;

import cn.edu.hrbcu.es.invigilatemanagerment.pojo.Permission;
import cn.edu.hrbcu.es.invigilatemanagerment.service.IPermissionService;
import cn.edu.hrbcu.es.invigilatemanagerment.service.ITeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authorization.AuthorityAuthorizationManager;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.List;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    /*@Bean
    public UserDetailsService userDetailsService(){
        DBUserDetailsManager manager = new DBUserDetailsManager();
        return manager;
    }*/
    @Autowired
    private PermissionFilterInvocationSecurityMetadataSource permissionFilterInvocationSecurityMetadataSource;
    @Autowired
    private PermissionAccessDecisionManager permissionAccessDecisionManager;
    @Autowired
    private MyAccessDeniedHandler myAccessDeniedHandler;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
        /*http.authorizeHttpRequests(
            authorize -> authorize
                    .requestMatchers("/assets/**").permitAll()
                    .anyRequest().authenticated()
        )
                .formLogin(form -> {
                    form.loginPage("/login").permitAll();//无需授权
                }); // 使用表单授权方式
                //.httpBasic(Customizer.withDefaults()) // 使用基本授权方式
        ;*/


        // login 登录页面需要匿名访问
        // permitAll 具有所有权限，也就可以匿名访问
        // anyRequest 任何请求，所有请求
        // authenticated 认证【登录】
        http.authorizeRequests(authorizeHttpRequests-> {
                    authorizeHttpRequests.requestMatchers("/static/**").permitAll();
                    authorizeHttpRequests.requestMatchers("/ExamInfo/toQueryAllExamInfoForStudent").permitAll();
                    authorizeHttpRequests.requestMatchers("/ExamInfo/queryAllExamInfoForStudent").permitAll();
                    authorizeHttpRequests.requestMatchers("/login").permitAll();
                    authorizeHttpRequests.requestMatchers("/toRegister").permitAll();
                    authorizeHttpRequests.requestMatchers("/Teacher/doRegister").permitAll();
                    authorizeHttpRequests.anyRequest().authenticated().withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                        @Override
                        public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                            object.setSecurityMetadataSource(permissionFilterInvocationSecurityMetadataSource); //动态获取url权限配置
                            object.setAccessDecisionManager(permissionAccessDecisionManager); //权限判断
                            return object;
                        }
                    });
                }
        );
        // loginPage 登录页面
        // loginProcessingUrl 登录接口 过滤器
        http.formLogin(formLogin->
                formLogin
                        .loginPage("/login")
                        .loginProcessingUrl("/login")
                        .defaultSuccessUrl("/index")
                        .permitAll()
        );
        http.exceptionHandling(exceptionHandling -> exceptionHandling
                .accessDeniedHandler(myAccessDeniedHandler)
        );

        http.logout(conf->{
            conf.logoutUrl("/logout");
            conf.logoutSuccessUrl("/login");
            conf.invalidateHttpSession(true);
            conf.permitAll();
        });


        // 跨域漏洞防御 关闭
        http.csrf(csrf -> csrf.disable());
        // 退出
        http.logout(logout->logout.invalidateHttpSession(true));

        http.rememberMe(conf->{
           conf.rememberMeParameter("remember-me");
        });
        return http.build();
    }



   /* @Bean//密码编码器，不解析密码
    public PasswordEncoder passwordEncoder(){
        //return NoOpPasswordEncoder.getInstance();
        return new BCryptPasswordEncoder();
    }*/


}